from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models


# 权限拓展

class TimeBaseModel(models.Model):
    """时间基类"""
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    update_time = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        abstract = True


#
#
# class MenuModel(TimeBaseModel):
#     """菜单表"""
#
#     url = models.CharField(_('地址'), max_length=150, null=True, blank=False)
#     icon = models.CharField(_('图标'), max_length=50, null=True, blank=False)
#     caption = models.CharField(_('标题'), max_length=50)
#     parent = models.ForeignKey(verbose_name=_('父级'), to='self', on_delete=models.CASCADE)
#
#
# class PermModel(TimeBaseModel):
#     """权限表"""
#
#     caption = models.CharField(_('权限标题'), max_length=50)
#     code = models.CharField(_('权限代码'), max_length=50)
#
#
# class RoleModel(TimeBaseModel):
#     """角色表"""
#     caption = models.CharField(_('角色名'), max_length=50)
#     perm = models.ManyToManyField(
#         PermModel,
#         verbose_name=_('权限'),
#         blank=True,
#     )
#     menu = models.ManyToManyField(
#         MenuModel,
#         verbose_name=_('菜单'),
#         blank=True,
#     )
#

class AdminUserManager(BaseUserManager):
    def create_user(self, account, name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        user = self.model(
            account=account,
            name=name
        )
        user.set_password(password)
        user.is_active = True
        user.save(using=self._db)
        return user

    def create_superuser(self, account, name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            account=account,
            name=name
        )
        user.set_password(password)
        user.is_superuser = True
        user.save(using=self._db)
        return user


# class PermMixin(models.Model):
#     """权限"""
#
#     is_superuser = models.BooleanField(
#         _('superuser status'),
#         default=False,
#         help_text=_(
#             'Designates that this user has all permissions without '
#             'explicitly assigning them.'
#         ),
#     )
#     role = models.ManyToManyField(
#         RoleModel,
#         verbose_name=_('Role'),
#         blank=True,
#         help_text=_(
#             'The Role this user belongs to. A user will get all permissions '
#             'granted to each of their groups.'
#         ),
#         related_name="person",
#     )
#     user_perm = models.ManyToManyField(
#         PermModel,
#         verbose_name=_('user permissions'),
#         blank=True,
#         help_text=_('Specific permissions for this user.'),
#         related_name="person",
#     )
#
#     user_enum = models.ManyToManyField(
#         MenuModel,
#         verbose_name=_('user menu'),
#         blank=True,
#         help_text=_('Specific menu for this user.'),
#         related_name="person",
#     )
#
#     class Meta:
#         abstract = True
#
#     # @cached_property
#     def get_all_perm(self):
#         """得到所有权限"""
#         perm_list = []
#         role_perm = self.role.all()
#         user_perm = self.user_perm.all()
#         for i in role_perm:
#             perm_list.extend([item for item in i.perm.all()])
#         for i in user_perm:
#             perm_list.append(i)
#         return perm_list
#
#     # @cached_property
#     def get_all_enum(self):
#         """得到所有菜单"""
#         enum_list = []
#         role_enum = self.role.all()
#         user_enum = self.user_enum.all()
#         for i in role_enum:
#             enum_list.extend([item for item in i.enum.all()])
#         for i in user_enum:
#             enum_list.append(i)
#         return enum_list
#
#     def has_perm(self, perm):
#         # Active superusers have all permissions.
#         if self.is_active and self.is_superuser:
#             return True
#         # Otherwise we need to check the backends.
#         return self._has_perm(perm)
#
#     def _has_perm(self, perm):
#         if perm not in self.get_all_perm:
#             return False
#         return True
#
#     def has_perms(self, perm_list):
#         """
#         Return True if the user has each of the specified permissions. If
#         object is passed, check if the user has all required perms for it.
#         """
#         return all(self.has_perm(perm) for perm in perm_list)
#
#     def has_enum(self, enum):
#         # Active superusers have all permissions.
#         if self.is_active and self.is_superuser:
#             return True
#         # Otherwise we need to check the backends.
#         return self._has_enum(enum)
#
#     def _has_enum(self, enum):
#         """检查是否"""
#         if enum not in self.get_all_enum:
#             return False
#         return True
#
#     def has_enums(self, enum_list):
#         """检查用户是否有传入的菜单列表的权限"""
#         return all(self.has_enum(enum) for enum in enum_list)
#


class PersonModel(AbstractBaseUser, PermissionsMixin):
    """人员表"""
    USERNAME_FIELD = 'account'  # 用户唯一标识列
    REQUIRED_FIELDS = ['name']

    role_choices = (
        (10, '开发人员'),
        (20, '测试人员'),
        (30, '项目管理员'),
        (40, '超级管理员'),
    )

    account = models.CharField(verbose_name='账号', max_length=18, unique=True)
    name = models.CharField(verbose_name='姓名', max_length=11)
    # first_name = models.CharField(verbose_name='姓名', max_length=11)
    role = models.IntegerField(verbose_name='角色', choices=role_choices, default=40)
    phone = models.CharField(verbose_name='电话号码', max_length=11, blank=True, null=True)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    update_time = models.DateTimeField('资料更新时间', auto_now=True)

    is_active = models.BooleanField(default=True, help_text='是否允许登录')  # 是否激活

    objects = AdminUserManager()

    @property
    def first_name(self):
        return self.name[:1]

    @property
    def last_name(self):
        return self.name[1:]

    def __str__(self):
        return self.account

    def get_full_name(self):
        """
        字符串, 用于标示用户
        """
        return '{}-{}'.format(self.name, self.account)

    def get_short_name(self):
        """字符串, 非正式的标识用户, 也可以返回和get_full_name()相同的值"""
        return self.account

    @property
    def is_staff(self):
        """是否允许登录"""
        return True

    class Meta:
        verbose_name = "人员信息"
        verbose_name_plural = verbose_name
